import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WordFrequencyCounter {

    public static void main(String[] args) {
        // 文件路径
        String filePath = "file.txt";

        // 创建一个HashMap来存储单词和频率
        Map<String, Integer> wordFrequencyMap = new HashMap<>();

        // 使用指定字符集读取文件
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(filePath), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 使用正则表达式分割字符串为单词
                String[] words = line.toLowerCase().split("\\W+"); // 匹配所有非单词字符

                for (String word : words) {
                    if (!word.isEmpty()) { // 排除空字符串
                        wordFrequencyMap.put(word, wordFrequencyMap.getOrDefault(word, 0) + 1);
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("文件读取出错: " + e.getMessage());
            return;
        }

        // 打印统计结果，格式化输出
        System.out.printf("%-20s%-10s%n", "单词", "出现频率");
        wordFrequencyMap.forEach((word, frequency) -> System.out.printf("%-20s%-10d%n", word, frequency));
    }
}
